package com.zhao.algorithm.utils

import java.sql.{Connection, DriverManager}

import com.typesafe.config.{Config, ConfigFactory}
import java.util

/**
 * Description: <br/>
 * Copyright (c) ，2020 ， 赵 <br/>
 * This program is protected by copyright laws. <br/>
 * Date： 2020/11/23 10:22
 *
 * @author 柒柒
 * @version : 1.0
 */

object MetadataJDBCUtil {
  val load: Config = ConfigFactory.load("jdbc.properties")

  private val max_connection = 10 //连接池中连接存放数
  private val connection_num = 10 //产生连接数
  private var current_num = 0 //当前连接池已产生的连接数
  private val pools = new util.LinkedList[Connection] //连接池


  /**
   * 加载驱动
   */
  private def before(): Unit = {
    if (current_num >= max_connection && !pools.isEmpty()) {
      print("busyness")
      Thread.sleep(2000)
      before() //递归调用自己
    } else {
      Class.forName(load.getString("db.metadata.default.driver"))
    }
  }

  /**
   * 获得连接数
   */
  private def initConn(): Connection = {
    val connection: Connection = DriverManager.getConnection(
      load.getString("db.metadata.default.url"),
      load.getString("db.metadata.default.user"),
      load.getString("db.metadata.default.password")
    )

    connection
  }

  /**
   * 初始化连接池
   */
  private def initConnectionPool(): util.LinkedList[Connection] = AnyRef.synchronized({
    if (pools.isEmpty) {
      before()
      for (i <- 1 to connection_num) {
        pools.push(initConn())
        current_num += 1
      }
    }
    pools
  })

  /**
   * 获得连接
   */
  def getConn(): Connection = {
    initConnectionPool()
    //计数器递减1
    current_num -= 1
    pools.poll() //与此同时,从连接池中删除一个连接的实例
  }

  /**
   * 释放连接
   */
  def releaseCon(con: Connection): Unit = {
    pools.push(con)
  }
}
